<template>
  <div>
    <vxe-grid v-bind="gridOptions" ref="xGrid">
      <template #form>
        <vxe-form ref="formRef" v-bind="formOptions">
          <template #action>
            <vxe-button status="primary" @click="searchEvent">搜索</vxe-button>
            <vxe-button @click="resetEvent">重置</vxe-button>
          </template>
        </vxe-form>
      </template>
    </vxe-grid>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onActivated, onMounted } from 'vue'
import type { VxeGridProps, VxeFormInstance, VxeGridInstance } from 'vxe-table'
import type { VxeFormProps } from 'vxe-pc-ui'

interface RowVO {
  id: string
  name: string
  role: string
  sex: string
  num: string
  address: string
}

interface FormDataVO {
  name: string
  role: string
  sex: string
  num: string
  address: string
}
const xGrid = ref<VxeGridInstance>()
const formRef = ref()

const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    name: '',
    role: '',
    sex: '',
    num: '',
    address: ''
  },
  items: [
    { field: 'name', title: '名称', itemRender: { name: 'VxeInput' } },
    { field: 'sex', title: '性别', itemRender: { name: 'VxeInput' } },
    { field: 'age', title: '年龄', itemRender: { name: 'VxeInput' } },
    { slots: { default: 'action' } }
  ]
})

const gridOptions = reactive<VxeGridProps<RowVO>>({
  id: 'DealerManageNameT',
  pagerConfig: {
    pageSizes: [10, 50, 100]
  },
  showOverflow: true,
  toolbarConfig: {},
  customConfig: {},
  border: true,
  height: 500,
  columns: [
    { field: 'seq', type: 'seq', width: 70 },
    { field: 'name', title: 'Name' },
    { field: 'sex', title: 'Sex' },
    { field: 'num', title: 'Num' },
    { field: 'address', title: 'Address' }
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      // 接收 Promise API
      query: async ({ page }) => {
        // const params = Object.assign({
        //   pageIndex: page.currentPage, // 额外参数
        //   pageSize: page.pageSize
        // })

        return await dealerPage()
      }
    }
  }
})

onActivated(() => {
  searchEvent()
})
onMounted(() => {
  searchEvent()
})

const dealerPage = () => {
  const data = [
    {
      id: '10001',
      name: 'Test1',
      role: 'Develop',
      sex: 'Man',
      num: '28',
      address: 'test abc'
    },
    {
      id: '10002',
      name: 'Test2',
      role: 'Test',
      sex: 'Women',
      num: '22',
      address: 'Guangzhou'
    }
  ]

  return data
}
const searchEvent = async () => {
  const $grid = xGrid.value!
  $grid.commitProxy('reload')
}

const resetEvent = () => {
  formRef.value.reset()
  xGrid.value!.commitProxy('reload')
}
</script>
